package cn.numeron.wxarticle.impl.wxarticle

import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.cachedIn
import cn.numeron.wxarticle.api.wxarticle.WxArticleParameter
import cn.numeron.wxarticle.api.wxarticle.WxArticleRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.*
import javax.inject.Inject

/**
 * 在构造里面声明需要注入的实例，可以提高属性初始化顺序的优先级
 * [WxArticleRepository]实例由Hilt自动注入
 * [SavedStateHandle]实例由Fragment的arguments提供
 */
@HiltViewModel
class WxArticleViewModel @Inject constructor(
    private val wxArticleRepository: WxArticleRepository,
    savedStateHandle: SavedStateHandle
) : ViewModel() {

    val parameterFlow: MutableStateFlow<WxArticleParameter>

    var keyword: String?
        get() = parameterFlow.value.keyword
        set(value) {
            parameterFlow.update {
                it.copy(keyword = value)
            }
        }

    init {
        val wxAuthorId = savedStateHandle.get<Int>("wx_author_id") ?: 408
        val wxArticleParameter = WxArticleParameter(wxAuthorId, null, 1)
        parameterFlow = MutableStateFlow(wxArticleParameter)
    }

    val wxArticleStatefulLiveData = parameterFlow
        //输入完后1秒后才开始处理
        .debounce(1000)
        .flatMapLatest {
            //转换到PagingData
            val pager = Pager(
                config = PagingConfig(pageSize = 16),
                initialKey = parameterFlow.value,
                pagingSourceFactory = {
                    wxArticleRepository.pagingSource(it)
                }
            )
            pager.flow
        }
        .cachedIn(viewModelScope)

    companion object {
        const val TAG = "WxArticleViewModel"
    }

}

